// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init()

var rp = require('request-promise');

// 云函数入口函数
exports.main = async (event, context) => {
  let info= encodeURIComponent(event.info)
  let aiList={
    qingyunke :`http://api.qingyunke.com/api.php?key=free&appid=0&msg=${info}`,
    tuling:`http://www.tuling123.com/openapi/api?key=28253c606be24e67b3752860803a33d3&info=${info}`
  };
  let url = aiList[event.ai] || aiList.tuling;
  return rp(url)
    .then(function (res) {
      console.log(res);
      res = JSON.parse(res);
      res.text = res.text || res.content;
      res.ceart = 'text';
      res.playStatus=false;
      if (res.text.indexOf(":周") != -1 || res.text.indexOf("天气 ：") != -1 ) {
        let city = event.ai == 'qingyunke' ? res.text.split("天气")[0]:res.text.split(":周")[0];
        return rp(`https://free-api.heweather.com/s6/weather?key=d469334ef67548578d65268f148b046f&location=${encodeURIComponent(city)}`)
          .then(function (re) {
            re = JSON.parse(re);
            res.city = city;
            let weather = { now: {}, forecast: [] }, daily=[];
            if (re.HeWeather6[0].status=="ok"){
              let weekList = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
              re.HeWeather6[0].daily_forecast.forEach(function (item) {
                let date='xx/xx',month = 'xx', day = 'xx', week = '周八', tmp=0,pic='';
                date = item.date;
                month=date.split("-")[1];
                day = date.split("-")[2];
                // date= new Date(Date.parse(date.replace(/-/g, "/")));
                week = new Date(date).getDay();
                week = weekList[weekList];
                pic = item.cond_code_d;
                tmp = Math.ceil((parseInt(item.tmp_min) + parseInt(item.tmp_max))/2);
                daily.push({ date, month, day, week, pic, tmp, cond_txt_d: item.cond_txt_d, tmp_min: item.tmp_min, tmp_max: item.tmp_max});
              });
              daily[0].tmp = re.HeWeather6[0].now.tmp;
              weather.now = daily[0];
              weather.forecast = daily.slice(1, 5);
              res.ceart = 'weather';
            }
            res.weather = weather;
            return res;
          })
          .catch(function (err) {
            console.error(err);
          });
      } 
      return res;
    })
    .catch(function (err) {
      console.error(err);
    });
}